﻿using System;
using System.Collections.ObjectModel;
using System.Net;
using System.Windows;
using System.Windows.Controls;
using System.Xml.Linq;

namespace CoverFlowClient
{
    public partial class MainPage : UserControl
    {
        ObservableCollection<MovieTrailer> trailers;
        public MainPage()
        {
            InitializeComponent();

            trailers = new ObservableCollection<MovieTrailer>();
            flowControl.ItemsSource = trailers;
            flowControl2.ItemsSource = trailers;
            Loaded += new RoutedEventHandler(MainPage_Loaded);
        }
        
        void MainPage_Loaded(object sender, RoutedEventArgs e)
        {
            var webClient = new WebClient();
            webClient.DownloadStringCompleted += new DownloadStringCompletedEventHandler(WebClientDownloadStringCompleted);
            var xmlUri = new Uri(Application.Current.Host.Source, "../CoverFlowService.svc/Trailers");
            webClient.DownloadStringAsync(xmlUri);
        }
        void WebClientDownloadStringCompleted(object sender, DownloadStringCompletedEventArgs e)
        {
            if (e.Error != null)
            {
                MessageBox.Show("There was an error retrieving xml");
                return;
            }
            var xDoc = XDocument.Parse(e.Result);
            foreach (var xMovieInfo in xDoc.Descendants("movieinfo"))
            {
                try
                {
                    var trailer = new MovieTrailer(xMovieInfo);
                    trailers.Add(trailer);
                }
                catch { }
            }
            flowControl.SelectedIndex = 0;
            flowControl2.SelectedIndex = 0;
        }
        
    }
}
